package demo.md5auth;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

/**
 * Created by stephen on 2021-04-04 23:18 .
 * Description:
 */
public class CustomMd5Realm extends AuthorizingRealm {

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 主身份信息
        String primaryPrincipal = (String) principals.getPrimaryPrincipal();
        // 权限信息
        SimpleAuthorizationInfo authorInfo = new SimpleAuthorizationInfo();
        authorInfo.addRole("admin");
        authorInfo.addRole("user");

        // 添加权限字符串 语法 资源标识符:操作:资源类型
        authorInfo.addStringPermission("user:*:*");

        return authorInfo;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 获取用户名
        String principal = (String) token.getPrincipal();
        // 根据用户名查询db
        if ("zhangsan".equals(principal)) {
            return new SimpleAuthenticationInfo(principal, // 用户名
                    "894b3913a4a13b25dc6186d11835c209", // db中md5 + salt + 散列后的密码
                    ByteSource.Util.bytes("abc"), // 随机盐
                    this.getName()); // realm的名字
        }
        return null;
    }
}
